package com.lcxsoft.partnerservice.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lcxsoft.commonutils.JwtUtils;
import com.lcxsoft.commonutils.R;
import com.lcxsoft.feign.clients.UserClient;
import com.lcxsoft.partnerservice.entity.PartnerUser;
import com.lcxsoft.partnerservice.entity.Withdrawal;
import com.lcxsoft.partnerservice.query.PartnerAddQuery;
import com.lcxsoft.partnerservice.query.PartnerQuery;
import com.lcxsoft.partnerservice.query.WithdrawalQuery;
import com.lcxsoft.partnerservice.service.PartnerUserService;
import com.lcxsoft.partnerservice.service.WithdrawalService;
import com.lcxsoft.partnerservice.url.PartnerServiceURL;
import com.lcxsoft.partnerservice.vo.WithdrawalVo;
import com.mysql.cj.util.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lcx
 * @since 2022-01-31
 */
@RestController
@RequestMapping(PartnerServiceURL.packageUrl)
public class PartnerUserController {

    @Resource
    private PartnerUserService partnerUserService;

    @Resource
    private WithdrawalService withdrawalService;

    @Resource
    private UserClient userClient;

    /**
     * 添加合伙人
     * @param query
     * @return
     */
    @PostMapping(PartnerServiceURL.PartnerUrl.addPartner)
    public R addPartner(PartnerAddQuery query){
        return partnerUserService.insertPartner(query);
    }

    /**
     * 获取合伙人列表
     * @param query
     * @return
     */
    @PostMapping(PartnerServiceURL.PartnerUrl.queryPartnerList)
    public R addPartner(PartnerQuery query){
        return partnerUserService.findPartnerList(query);
    }

    /**
     * 登录
     * @param phone
     * @param password
     * @return
     */
    @PostMapping(PartnerServiceURL.PartnerUrl.login)
    public R login(String phone, String password){
        return partnerUserService.doLogin(phone, password);
    }

    /**
     * 获取用户信息
     * @param request
     * @return
     */
    @RequestMapping(PartnerServiceURL.PartnerUrl.partnerInfo)
    public R userInfo(HttpServletRequest request){
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        if (StringUtils.isNullOrEmpty(userId)){
            return R.error().message("认证信息有误");
        }
        PartnerUser partnerUser = partnerUserService.getById(userId);
        return R.ok().data("roles", "[admin]").data("name", partnerUser.getPartnerUserNickname()).data("avatar", partnerUser.getPartnerUserAvatar());
    }

    /**
     * 根据id获取实体
     * @param params
     * @return
     */
    @PostMapping(PartnerServiceURL.PartnerUrl.queryPartnerById)
    public PartnerUser queryPartnerById(@RequestBody Map<String, String> params){
        String partnerId = params.get("partnerId");
        return partnerUserService.getOne(new LambdaQueryWrapper<PartnerUser>().eq(PartnerUser::getPartnerUserId, partnerId));
    }

    /**
     * 根据shcoolid和总金额进行给代理人加钱
     * @param params
     * @return
     */
    @PostMapping(PartnerServiceURL.PartnerUrl.addMoneyByDormitoryId)
    public boolean addMoneyByDormitoryId(@RequestBody Map<String, Object> params){
        String dormitoryId = (String) params.get("dormitoryId");
        BigDecimal ordersTottle = new BigDecimal( (Double) params.get("ordersTottle"));
        String schoolId = userClient.querySchoolIdByDormitoryId(dormitoryId);
        PartnerUser partnerUser = partnerUserService.getOne(new LambdaQueryWrapper<PartnerUser>().eq(PartnerUser::getSchoolId, schoolId));
        BigDecimal nowMoney = partnerUser.getPartnerUserBalance().add(ordersTottle);
        partnerUser.setPartnerUserBalance(nowMoney);
        partnerUser.setUpdatetime(LocalDateTime.now());
        return partnerUserService.updateById(partnerUser);
    }

    /**
     * 申请提现
     * 接口未联调
     * @param query
     * @return
     */
    @PostMapping(PartnerServiceURL.PartnerUrl.startWithdrawal)
    @Transactional
    public R startWithdrawal(WithdrawalQuery query, HttpServletRequest request){
        String partnerId = JwtUtils.getMemberIdByJwtToken(request);
        //拿到合伙人实体
        PartnerUser partnerUser = partnerUserService.getOne(new LambdaQueryWrapper<PartnerUser>().eq(PartnerUser::getPartnerUserId, partnerId));
        //判断用户余额够不够提现
        if (partnerUser.getPartnerUserBalance().compareTo(query.getWithdrawalTottle()) == -1){
            return R.error().message("余额不足，无法提现");
        }
        //生成提现订单
        Withdrawal withdrawal = new Withdrawal();
        withdrawal.setWithdrawalId(UUID.randomUUID().toString().toUpperCase());
        withdrawal.setPartnerUserId(partnerId);
        withdrawal.setCreatetime(LocalDateTime.now());
        //待管理员确认打款
        withdrawal.setStatus("0");
        withdrawal.setWithdrawalTottle(query.getWithdrawalTottle());
        withdrawal.setWithdrawalAccount(query.getWithdrawalAccount());
        //设置实际到账
        BigDecimal actualArrival = query.getWithdrawalTottle().multiply(BigDecimal.valueOf((100 - partnerUser.getPartnerRate()) / 100));
        withdrawal.setActualArrival(actualArrival);
        withdrawalService.save(withdrawal);
        //给合伙人账户扣款
        BigDecimal nowMoney = partnerUser.getPartnerUserBalance().subtract(query.getWithdrawalTottle());
        partnerUser.setPartnerUserBalance(nowMoney);
        partnerUser.setUpdatetime(LocalDateTime.now());

        partnerUserService.updateById(partnerUser);
        return R.ok().message("申请提现成功，在3个工作日内到账！");
    }

    /**
     * 查询提现列表空参查询全部
     * 接口未联调
     * @param request
     * @return
     */
    @PostMapping(PartnerServiceURL.PartnerUrl.queryWithdrawalList)
    public R queryWithdrawalList(HttpServletRequest request){
        String partnerUserId = JwtUtils.getMemberIdByJwtToken(request);
        //返回数据
        List<WithdrawalVo> withdrawalVoList = new ArrayList<>();
        //如果partnerUserId为空则查询全部
        List<Withdrawal> withdrawalList;
        if (StringUtils.isNullOrEmpty(partnerUserId)){
            withdrawalList = withdrawalService.list(null);
        }else {
            withdrawalList = withdrawalService.list(new LambdaQueryWrapper<Withdrawal>().eq(Withdrawal::getPartnerUserId, partnerUserId));

        }
        for (Withdrawal withdrawal : withdrawalList) {
            WithdrawalVo withdrawalVo = new WithdrawalVo();
            BeanUtil.copyProperties(withdrawal, withdrawalVo);
            PartnerUser partnerUser = partnerUserService.getOne(new LambdaQueryWrapper<PartnerUser>().eq(PartnerUser::getPartnerUserId, withdrawal.getPartnerUserId()));
            BeanUtil.copyProperties(partnerUser, withdrawalVo);
            if ("0".equals(withdrawalVo.getStatus())){
                withdrawalVo.setStatusText("待打款");
            }
            if ("1".equals(withdrawalVo.getStatus())){
                withdrawalVo.setStatusText("已打款");
            }
            withdrawalVoList.add(withdrawalVo);
        }
        return R.ok().data("withdrawalVoList", withdrawalVoList);
    }

    /**
     * 确认打款
     * 接口未联调
     * @param withdrawalId
     * @return
     */
    @PostMapping(PartnerServiceURL.PartnerUrl.confirmWithdrawal)
    public R confirmWithdrawal(String withdrawalId){
        Withdrawal withdrawal = withdrawalService.getOne(new LambdaQueryWrapper<Withdrawal>().eq(Withdrawal::getWithdrawalId, withdrawalId));
        if ("1".equals(withdrawal.getStatus())){
            return R.error().message("已经打款，请勿重复打款！");
        }
        withdrawal.setStatus("1");
        withdrawal.setUpdatetime(LocalDateTime.now());
        return withdrawalService.updateById(withdrawal) ? R.ok().message("确认打款成功！").code(200) : R.error().message("打款失败！");
    }

    /**
     * 查询用户当前余额
     * @param request
     * @return
     */
    @PostMapping(PartnerServiceURL.PartnerUrl.queryCurrentBalance)
    public R queryCurrentBalance(HttpServletRequest request){
        String userId = JwtUtils.getMemberIdByJwtToken(request);
        PartnerUser partnerUser = partnerUserService.getOne(new LambdaQueryWrapper<PartnerUser>().eq(PartnerUser::getPartnerUserId, userId));
        return R.ok().data("partnerUserBalance", partnerUser.getPartnerUserBalance());
    }

}

